package com.etoak.service.impl;

import cn.hutool.json.JSONUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.redis.service.RedisService;
import com.etoak.common.web.context.LoginUserContext;
import com.etoak.dto.CartDTO;
import com.etoak.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    RedisService redisService;

    @Override
    public void saveOrUpdate(CartDTO cartDTO) {
        redisService.hset(getKey(),
                cartDTO.getDishesId().toString(),
                JSONUtil.toJsonStr(cartDTO));
    }

    @Override
    public List<CartDTO> list() {
        return redisService.hvals(getKey())
                .stream().map(str->JSONUtil.toBean(str,CartDTO.class))
                .toList();
    }

    @Override
    public void deleteDishes(String dishesId) {
        redisService.hedl(getKey(),dishesId);
    }

    @Override
    public void clearCart() {
        redisService.del(getKey());
    }

    private String getKey(){
        return CommonConstant.REDIS_CART_KEY_PREFIX+ LoginUserContext.getUserId();
    }
}
